package com.zues.daiommiddleware.linstener;


import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.nls.client.protocol.asr.SpeechTranscriberListener;
import com.alibaba.nls.client.protocol.asr.SpeechTranscriberResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Properties;

/**
 * 语音识别监听器-发送接口方案
 *
 * @author: zues
 * @date: 2024/9/6
 */
@Slf4j
@Component
public class SpeechListener extends SpeechTranscriberListener {

    @Override
    public void onTranscriberStart(SpeechTranscriberResponse speechTranscriberResponse) {
    }

    /**
     * 识别出一句话的开始.服务端在识别到一句话的开始时,会返回此消息
     * response.getTaskId()
     * 重要提示： task_id很重要，是调用方和服务端通信的唯一ID标识，当遇到问题时，需要提供此task_id以便排查
     * 每次开启语音识别会生成一个唯一的task_id
     */
    @Override
    public void onSentenceBegin(SpeechTranscriberResponse response) {
//        System.out.println("task_id: " + response.getTaskId() + ", name: " + response.getName() + ", status: " + response.getStatus());
    }

    /**
     * 识别出一句话.服务端会智能断句,当识别到一句话结束时会返回此消息
     */
    @Override
    public void onSentenceEnd(SpeechTranscriberResponse response) {
        String content = response.getTransSentenceText();
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("content", content);
        //获取接口配置url
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(new ClassPathResource("application.yml"));
        factory.afterPropertiesSet();
        Properties properties = factory.getObject();
        //当key=aliyun.contentUrl时赋值
        assert properties != null;
        String contentUrl = properties.getProperty("aliyun.contentUrl");
        //调用远程接口
        HttpRequest.get(contentUrl)
                .header(Header.USER_AGENT, "3hui http")//头信息，多个头信息多次调用此方法即可
                .form(paramMap)//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();
    }

    /**
     * TODO 识别出中间结果.服务端识别出一个字或词时会返回此消息.仅当setEnableIntermediateResult(true)时,才会有此类消息返回
     */
    @Override
    public void onTranscriptionResultChange(SpeechTranscriberResponse response) {
    }

    /**
     * 识别结束.服务端识别结束时会返回此消息
     */
    @Override
    public void onTranscriptionComplete(SpeechTranscriberResponse response) {
//        System.out.println("task_id: " + response.getTaskId() + ", name: " + response.getName() + ", status: " + response.getStatus());
    }

    /**
     * 识别失败.服务端识别失败时,会返回此消息
     */
    @Override
    public void onFail(SpeechTranscriberResponse response) {
        System.out.println("读取发生错误了,task_id: " + response.getTaskId() + ", name: " + response.getName() + ", status: " + response.getStatus());
    }
}
